import React, { useState, useEffect } from "react";
import Select from "../../Select";
import { useErrmsgStyles } from "./styles";

import type { NestFilterOptions } from "../type";

export default function SelectComponent({
  value,
  options,
  multiple,
  disabled,
  errmsg,
  onChange,
}: {
  value: Array<string | number>;
  options?: ((v?: string) => Promise<NestFilterOptions>) | NestFilterOptions;
  multiple?: boolean;
  disabled?: boolean;
  errmsg?: string;
  onChange: (v: Array<string | number>) => void;
}) {
  const [opts, setOpts] = useState<NestFilterOptions>([]);
  const classes = useErrmsgStyles();

  const handler = (v: string | number | Array<string | number>) => {
    onChange(Array.isArray(v) ? v : [v]);
  };

  useEffect(() => {
    if (options) {
      if (typeof options == "function") {
        options().then((r) => setOpts(r));
      } else {
        setOpts(options);
      }
    }
  }, [options]);

  const onInputChange = (text: string) => {
    if (!options) return;
    if (typeof options == "function") {
      options(text).then((r) => setOpts(r));
    } else {
      const opts = options.filter(
        (i) => i.label.includes(text) || String(i.value).includes(text)
      );
      setOpts(opts);
    }
  };

  if (multiple) {
    return (
      <>
        <Select
          value={value}
          search
          multiple
          onChange={handler}
          options={opts}
          disabled={disabled}
          onInputChange={onInputChange}
        />
        {errmsg && <div className={classes.errmsg}>{errmsg}</div>}
      </>
    );
  } else {
    return (
      <>
        <Select
          value={value[0]}
          search
          onChange={handler}
          options={opts}
          disabled={disabled}
          onInputChange={onInputChange}
        />
        {errmsg && <div className={classes.errmsg}>{errmsg}</div>}
      </>
    );
  }
}
